var config = {
  aliyunServerURL: '',
  AccessKeySecret: '',
  accessid: '',
	policyBase64:'',
	signature:'',
  timeout: 87600 ,
	expiration:'',
	SecurityToken:''
};

import { encode } from './base64';
import './hmac.js';
import './sha1.js';
import Crypto from './crypto';
import useCurrentInstance from '../../utils/useCurrentInstance';
const { proxy } = useCurrentInstance()

/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
 *@param - dir:表示要传到哪个目录下
 *@param - successc:成功回调
 *@param - failc:失败回调
 */

const uploadFile = function (filePath, type,successc, failc) {
  if (!filePath || filePath.length < 9) {
    proxy.$message({
      type:'error',
      message:'文件错误'
    })
    return;
  }




	proxy.$api.uploadToken({file_type:type}).then(res => {
		if(res.code == 200){
			config.aliyunServerURL = `https://${res.result.token.Bucket}.${res.result.token.Region}.aliyuncs.com/`
			config.accessid = res.result.token.AccessKeyId
			config.AccessKeySecret = res.result.token.AccessKeySecret
			config.expiration = res.result.token.Expiration
			config.SecurityToken = res.result.token.SecurityToken
			config.policyBase64 = getPolicyBase64()
			config.signature = getSignature(config.policyBase64)

			//图片名字 可以自行定义，     这里是采用当前的时间戳 + 150内的随机数来给图片命名的
			const aliyunFileKey = res.result.token.Path + new Date().getTime() + Math.floor(Math.random() * 150) + (type)
      successc(config.aliyunServerURL+aliyunFileKey);
		}else{
      proxy.$message({
        type:'error',
        message:res.msg
      })
		}
	})
}

const getPolicyBase64 = function () {
  const policyText = {
    "expiration": config.expiration, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
      ["content-length-range", 0, 10 * 1024 * 1024] // 设置上传文件的大小限制,5mb
    ]
  };
  const policyBase64 = encode(JSON.stringify(policyText));
  return policyBase64;
}

const getSignature = function (policyBase64) {
  const accesskey = config.AccessKeySecret;

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);
  return signature;
}

module.exports = uploadFile;
